package com.rabit.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.xml.crypto.Data;

/***
 * 线程内共享数据
 * 
 * @author rabit
 *
 */
public class ThreadScopeShareData {
	static ThreadLocal<Integer> x = new ThreadLocal<>();
	static ThreadLocal<MyTHreadScopeData> myThreadScopeData = new ThreadLocal<>();

	public static void main(String[] args) {
		for (int i = 0; i < 2; i++) {

			new Thread(new Runnable() {
				@Override
				public void run() {
					int data = new Random().nextInt();
					System.out.println(Thread.currentThread().getName() + "-- main put data" + data);
					x.set(data);
					/*MyTHreadScopeData myData = new MyTHreadScopeData();
					myData.setName("name" + data);
					myData.setAge(data);
					myThreadScopeData.set(myData);*/
					MyTHreadScopeData.getInstance().setName("name" + data);
					MyTHreadScopeData.getInstance().setAge(data);
					new A().get();
					new B().get();

				}
			}).start();
		}
	}

	static class A {
		public void get() {
			int data = x.get();
			System.out.println(Thread.currentThread().getName() + "--A get data" + data);
			MyTHreadScopeData myData =MyTHreadScopeData.getInstance();
			System.out.println("A from" + Thread.currentThread().getName() + "GetMyData" + myData.getName() + ","
					+ myData.getAge());
		}
	}

	static class B {
		public void get() {
			int data = x.get();
			System.out.println(Thread.currentThread().getName() + "--B get data" + data);
			MyTHreadScopeData myData = MyTHreadScopeData.getInstance();
			System.out.println("B from" + Thread.currentThread().getName() + "GetMyData" + myData.getName() + ","
					+ myData.getAge());
		}
	}

}

class MyTHreadScopeData {
	private MyTHreadScopeData() {

	}

	public static/* synchronized */MyTHreadScopeData getInstance() {
		MyTHreadScopeData instance=map.get();
		if (instance == null) {
			instance = new MyTHreadScopeData();
			map.set(instance);
		}
		return instance;
	}

	private static MyTHreadScopeData instance = null;
	private static ThreadLocal<MyTHreadScopeData> map=new ThreadLocal<>();
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}
